import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmcaddon,datetime,operator,xml,xml.sax.saxutils,htmlentitydefs
import simplejson as json
from BeautifulSoup import BeautifulStoneSoup
from BeautifulSoup import BeautifulSoup

def CATEGORIES():
        addDir('Titel','URL',2,'',1)
 
def XMLHTTPRESPONSE(url, mode=0):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        return link
   
def VIDEOLINKS(url1,start,limit,page):
    link=XMLHTTPRESPONSE(url1)
    soup = BeautifulSoup(link)
    infos=re.compile('href="(.*?)">(.*)</a></div><div class="item-size">').findall(link)
    print len(infos)
    for i in  range(len(infos),0,-1):
         print infos[i-1][0]
         addLink(infos[i-1][1],re.sub('" title="Open this file','',infos[i-1][0],1),0,'','')

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param


def addLink(name,url,mode ,iconimage,time,watched=0,infos=None):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        #overlay= {'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}
        infos={"Title": name, "Studio":"Wuala","Duration":time,"Genre":"Sport","Year":2011,"overlay":watched}
        if mode==0:
            u=url
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels=infos )
        #liz.setInfo( type="Video", infoLabels={"Title": name, "Studio":"MLB","Duration":time,"Genre":"Sport","Year":2011} )
        #liz.addContextMenuItems([("Search","XBMC.RunPlugin(%s?url=%s&mode=13)"%(sys.argv[0],'search'))])
        liz.setProperty('IsPlayable', 'true')
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
        return ok

def addDir(name,url,mode,iconimage,page):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&page="+str(page)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.addContextMenuItems([("Search","XBMC.RunPlugin(%s?url=%s&mode=13&name=Search&page=1)"%(sys.argv[0],'search'))],replaceItems=False)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

          
params=get_params()
url=None
name=None
mode=None
start=0
limit=100
page=1
try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        page=int(params["page"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Page: "+str(page)

if mode==None or url==None or len(url)<1:
        #CATEGORIES()
        VIDEOLINKS('https://www.wuala.com/wowawebdesign/Fireworks-Kurs?key=WibMYGhFrpO8',start,limit,page)
elif mode==2:
        print 'VOR'+url
        VIDEOLINKS(url,start,limit,page)
elif mode==3:
        VIDEOLINKS(url,name,limit*(page-1),limit*page,page)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
